//
//  RdbSubscribeProductRequest.swift
//  rdb-led-banner
//  获取商品信息
//  Created by radiobox3 on 2025/4/17.
//

import StoreKit
import Alamofire

enum RdbSubscribePeriodType: String{
    case weekly = "1"
    case monthly = "2"
    case yearly = "3"
}

class RdbSubscribeProductRequest: NSObject, SKProductsRequestDelegate{
    
    static let shared = RdbSubscribeProductRequest()
    
    //查询商品的列表
    var products: [SKProduct] = []
    //请求后的回调函数
    var requestCompleted: SubscribeCompletion?
    
    //构建产品请求对象，将要查询的产品信息发送给苹果
    lazy var productRequest: SKProductsRequest = {
        let request = SKProductsRequest(productIdentifiers: [
            RdbSubscribePeriodType.weekly.rawValue,
            RdbSubscribePeriodType.monthly.rawValue,
            RdbSubscribePeriodType.yearly.rawValue
        ])
        request.delegate = self
        return request
    }()
    
    //自定义方法: 发送请求
    func requestProduct(_ completion: SubscribeCompletion?){
        self.requestCompleted = completion
        if NetworkReachabilityManager.default?.isReachable == true {
            //有网络后发送请求
            if RdbSubscribeProductRequest.shared.products.isEmpty {
                self.productRequest.start()
            }else{
                self.requestCompleted?(true,nil)
            }
        }else{
            self.requestCompleted?(false, ["message": "badnetworking".localized])
        }
    }
    //自定义方法: 获取指定产品价格
    func getPriceText(period type: RdbSubscribePeriodType) -> String{
        let product = self.products.filter{ product in
            return product.productIdentifier == type.rawValue
        }.first
        

        let symbol = product?.priceLocale.currencySymbol ?? ""
        
        let price = product?.price.stringValue ?? ""
        
        let priceText = "\(symbol)\(price)"
        
        return priceText
    }
    //自定义方法: 计算year/week
    func getYearPricePerWeek(period type: RdbSubscribePeriodType) -> String{
        let product = self.products.filter{ product in
            return product.productIdentifier == type.rawValue
        }.first
        

        let symbol = product?.priceLocale.currencySymbol ?? ""
        
        guard let price = product?.price  else {
            
            return ""
        }
        return String(format: "\(symbol)%.2f", price.doubleValue / 52.0)
    }
    //自定义方法: 计算 month/week
    func getMonthPricePerWeek(period type: RdbSubscribePeriodType) -> String{
        let product = self.products.filter{ product in
            return product.productIdentifier == type.rawValue
        }.first
        

        let symbol = product?.priceLocale.currencySymbol ?? ""
        
        guard let price = product?.price  else {
            
            return ""
        }
        return String(format: "\(symbol)%.2f", price.doubleValue / 4.0)
    }
    
    
    //MARK: - SKProductsRequestDelegate
    //供苹果调用: 返回查询结果
    func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
        self.products = response.products
    }
    //供苹果调用: 请求完成
    func requestDidFinish(_ request: SKRequest) {
        self.requestCompleted?(true,nil)
    }
    //供苹果调用: 请求失败
    func request(_ request: SKRequest, didFailWithError error: any Error) {
        self.requestCompleted?(false, ["message": error.localizedDescription])
        print("product request fail")
    }
    
}
